package com.graduation.cdm.funactivity.view.mineview;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.graduation.cdm.funactivity.MyApplication;
import com.graduation.cdm.funactivity.R;
import com.graduation.cdm.funactivity.bean.User;
import com.graduation.cdm.funactivity.util.MultipartRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.graduation.cdm.funactivity.util.GlobalConstant.preUrl;
import static com.graduation.cdm.funactivity.util.xUtilsImageUtils.displayHead;

public class ModifyUserInfoActivity extends AppCompatActivity implements View.OnClickListener {

    User user;
    private ImageView ivUserPhoto;
    private EditText tvName;
    private TextView tvSex;
    private EditText tvPhone;
    private EditText tvEmail;
    private ImageView ivBack;
    private TextView tvOk;
    private RelativeLayout rlSex;
    Integer userId;

    private File file;
    private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";//temp file
    Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);//The Uri to store the big bitmap

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_user_info);

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //目录，文件名Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
            file = new File(Environment.getExternalStorageDirectory(), getPhotoFileName());
            imageUri = Uri.fromFile(file);
        }

        initView();
        getUserInfo();

    }

    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        return sdf.format(date) + ".png";
    }

    private void initView(){
        ivUserPhoto = ((ImageView)  findViewById(R.id.iv_user_photo));
        tvName = ((EditText) findViewById(R.id.tv_name));
        tvSex = ((TextView) findViewById(R.id.tv_add));
        tvPhone = ((EditText) findViewById(R.id.tv_mobile_phone));
        tvEmail = ((EditText) findViewById(R.id.tv_email));

        ivBack = ((ImageView) findViewById(R.id.iv_back1));
        tvOk = ((TextView) findViewById(R.id.tv_ok));
        rlSex = ((RelativeLayout) findViewById(R.id.rl_add));

        ivBack.setOnClickListener(this);
        rlSex.setOnClickListener(this);
        tvOk.setOnClickListener(this);
        ivUserPhoto.setOnClickListener(this);

    }

    private void getUserInfo(){
        Intent intent = getIntent();
        user = ((User) intent.getSerializableExtra("userInfo"));
        System.out.println("==user=="+user);
        if (user!=null){
            userId = user.getUserId();
            displayHead(ivUserPhoto,preUrl+user.getImageUrl());
            tvName.setText(user.getUserName().toString());
            tvSex.setText(user.getUserSex().toString());
            tvPhone.setText(user.getUserPhone().toString());
            tvEmail.setText(user.getUserEmail().toString());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back1:
                finish();
                break;
            case R.id.tv_ok:
                changeUserInfo();
                break;
            case R.id.iv_user_photo:
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setType("image/*");
                /*intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                        "image*//*");*/
                startActivityForResult(intent,1);
                break;
            case R.id.rl_add:
                showView();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (data != null) {
                    crop(data.getData());
                }
                break;
            case 2:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    System.out.println("extras"+extras);
                    if (extras != null) {
                        Bitmap bitmap = extras.getParcelable("data");
                        showImage(bitmap);
                    }
                }
                break;
        }
    }

    public void crop(Uri uri){
        //  intent.setType("image/*");
        //裁剪
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        intent.putExtra("crop", "true");

        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 2);
    }

    public void showImage(Bitmap bitmap) {
        ivUserPhoto.setImageBitmap(bitmap);//iv显示图片
        saveImage(bitmap);//保存文件
        System.out.println("file"+file);
        //uploadAvatarByMultipart();//上传服务器
    }

    public byte[] getImageBytes(Bitmap bmp){
        if(bmp==null){
            return null;
        }
        ByteArrayOutputStream baos =new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG,100,baos);
        byte[] imageBytes = baos.toByteArray();
        return imageBytes;
    }

    public void saveImage(Bitmap bitmap) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
    }


    private final String boundary ="apiclient-"+ System.currentTimeMillis();
    private final String mimeType ="multipart/form-data;boundary="+ boundary;
    private byte[] multipartBody;//保存内容的数组集合
    private Bitmap bitmap;//需要上传的图片
    private void uploadAvatarByMultipart(){
        String path = file.getAbsolutePath();
        bitmap = BitmapFactory.decodeFile(path);
        multipartBody =getImageBytes(bitmap);
        String url=preUrl+"user/uploadImage?userName="+file.getName();
        MultipartRequest multipartRequest = new MultipartRequest(url,ModifyPwdActivity.class,null,uploadAvatarByMultipartListener(),errorListener(),mimeType, multipartBody);
        MyApplication.getRequestQueue().add(multipartRequest);
    }

    private Response.Listener uploadAvatarByMultipartListener() {
        return new Response.Listener() {
            @Override
            public void onResponse(Object o) {
                Toast.makeText(getApplicationContext(),"成功！",Toast.LENGTH_SHORT).show();
                System.out.println(o.toString());
            }
        };
    }

    private Response.ErrorListener errorListener() {
        return new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getApplicationContext(),"失败！",Toast.LENGTH_SHORT).show();
                System.out.println(volleyError.toString());
            }
        };
    }



    public void showView() {
        final CharSequence[] items = {"男", "女"};
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setSingleChoiceItems(items,-1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                    case 0:
                        tvSex.setText("男");
                        break;
                    case 1:
                        tvSex.setText("女");
                        break;
                }
                dialog.dismiss();
            }
        });
        builder.show();


    }

    private void changeUserInfo(){
        uploadAvatarByMultipart();
        String url = preUrl+"user/changeUserInfo";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                System.out.println("=change="+s.trim());
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.get("result").toString().equals("true")) {
                        SharedPreferences sharedPreferences = getSharedPreferences("user_info",MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString("userName",tvName.getText().toString());
                        editor.putString("userSex",tvSex.getText().toString());
                        editor.putString("userPhone",tvPhone.getText().toString());
                        editor.putString("userEmail",tvEmail.getText().toString());
                        editor.putString("imgUrl","lib/imgs/"+file.getName());
                        editor.commit();

                        Intent intent1=new Intent();
                        setResult(100,intent1);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("userId",userId+"");
                map.put("userName",tvName.getText().toString());
                map.put("userSex",tvSex.getText().toString());
                map.put("userPhone",tvPhone.getText().toString());
                map.put("userEmail",tvEmail.getText().toString());
                map.put("imageUrl","lib/imgs/"+file.getName());
                return map;
            }
        };
        MyApplication.getRequestQueue().add(stringRequest);
    }

}
